package com.yx1996.web.servlet;

import com.yx1996.domain.PageBean;
import com.yx1996.domain.Product;
import com.yx1996.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Servlet implementation class ProductListByCidServlet
 */
public class ProductListByCidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductListByCidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("cid");
		String currentPageStr = request.getParameter("currentPage");
		if(currentPageStr==null){
			currentPageStr="1";
		}
		int currentCount=12;
		ProductService productService = new ProductService();
		PageBean<Product> PageBean = productService.findProductListByCid(cid,currentPageStr,currentCount);
		request.setAttribute("PageBean", PageBean);
		request.setAttribute("cid", cid);
		request.setAttribute("currentPage", currentPageStr);
		
		List<Product> historyPro = new ArrayList<Product>();
		Cookie[] cookies = request.getCookies();
			if(cookies!=null){
				for(Cookie cookie : cookies){
					if("pids".equals(cookie.getName())){
						String pids = cookie.getValue();
						String[] split = pids.split("-");
						for(String pid : split){
							Product pro = productService.findProduct(pid);
							historyPro.add(pro);
						}
					}
				}
			}
		request.setAttribute("historyPro", historyPro);
		request.getRequestDispatcher("product_list.jsp").forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
		
	}

}
